﻿namespace Fiddler
{
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;

    public class UIARRuleTester : Form
    {
        private Button btnSave;
        public ComboBox cbxPattern;
        private IContainer components;
        private Label label1;
        private Label label2;
        private Label lblStatus;
        private string sOriginalRule;
        private TextBox txtURL;

        public UIARRuleTester(ComboBox.ObjectCollection oItems, string sPattern)
        {
            this.InitializeComponent();
            this.sOriginalRule = sPattern;
            Utilities.SetCueText(this.cbxPattern, "URL Pattern (REGEX:, EXACT: or partial)");
            Utilities.SetCueText(this.txtURL, "URL against which the pattern will be tested");
            foreach (object obj2 in oItems)
            {
                this.cbxPattern.Items.Add(obj2);
            }
            this.cbxPattern.Text = sPattern;
            string fullUrl = null;
            if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();
                if ((text.Length < 0xffc) && ((text.StartsWith("http://") || text.StartsWith("https://")) || text.StartsWith("ftp://")))
                {
                    fullUrl = text;
                }
            }
            if (string.IsNullOrEmpty(fullUrl) && (1 == FiddlerApplication.UI.lvSessions.SelectedCount))
            {
                fullUrl = FiddlerApplication.UI.GetFirstSelectedSession().fullUrl;
            }
            if (string.IsNullOrEmpty(fullUrl))
            {
                fullUrl = FiddlerApplication.Prefs.GetStringPref("fiddler.ephemeral.autoresponder.LastTestURI", "http://example.com/path/page?param=1");
            }
            this.txtURL.Text = fullUrl;
            this.actTestMatch();
        }

        private void actTestMatch()
        {
            if (this.txtURL.Text.Length < 1)
            {
                this.lblStatus.Text = "Enter a test URL.";
            }
            else if (!this.txtURL.Text.Contains("://"))
            {
                this.lblStatus.Text = "Supply a fully-qualified URL (http://host/path)";
            }
            else if (this.cbxPattern.Text.Length < 1)
            {
                this.lblStatus.Text = "Enter a URL Pattern.";
            }
            else
            {
                string text = this.cbxPattern.Text;
                if (text.StartsWith("URLWithBody:", StringComparison.OrdinalIgnoreCase))
                {
                    text = Utilities.TrimAfter(text.Substring(12), ' ');
                }
                if (!this.isValidIfREGEX(text))
                {
                    this.lblStatus.Text = "Regular expression is not valid.";
                    this.cbxPattern.BackColor = Color.Orange;
                }
                else
                {
                    if (AutoResponder.CheckMatch(this.txtURL.Text, null, text))
                    {
                        this.txtURL.BackColor = Color.Aquamarine;
                        this.lblStatus.Text = string.Format("The pattern matches the test URL{0}.", this.cbxPattern.Text.StartsWith("URLWithBody:") ? " (Body not tested)" : string.Empty);
                    }
                    else
                    {
                        this.txtURL.BackColor = Color.Salmon;
                        this.lblStatus.Text = "The pattern does NOT match the test URL.";
                    }
                    this.btnSave.Enabled = this.cbxPattern.Text != this.sOriginalRule;
                }
            }
        }

        private void cbxPattern_TextChanged(object sender, EventArgs e)
        {
            this.cbxPattern.BackColor = Color.FromKnownColor(KnownColor.Window);
            this.actTestMatch();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.txtURL = new TextBox();
            this.btnSave = new Button();
            this.label1 = new Label();
            this.label2 = new Label();
            this.cbxPattern = new ComboBox();
            this.lblStatus = new Label();
            base.SuspendLayout();
            this.txtURL.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
            this.txtURL.Location = new Point(0x57, 0x26);
            this.txtURL.Name = "txtURL";
//            this.txtURL.Size = new Size(0x14f, 0x15);
            this.txtURL.TabIndex = 3;
            this.txtURL.Text = "http://example.com/path/page?param=1";
            this.txtURL.TextChanged += new EventHandler(this.cbxPattern_TextChanged);
            this.btnSave.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
           // this.btnSave.DialogResult = DialogResult.OK;
            this.btnSave.Enabled = false;
            this.btnSave.Location = new Point(0x13e, 70);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new Size(0x68, 0x17);
            this.btnSave.TabIndex = 4;
            this.btnSave.Text = "&Save Changes";
            this.btnSave.UseVisualStyleBackColor = true;
            this.label1.AutoSize = true;
            this.label1.Location = new Point(15, 15);
            this.label1.Name = "label1";
            this.label1.Size = new Size(0x45, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "&URL Pattern:";
            this.label1.TextAlign = ContentAlignment.MiddleRight;
            this.label2.AutoSize = true;
            this.label2.Location = new Point(15, 0x29);
            this.label2.Name = "label2";
            this.label2.Size = new Size(0x36, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "&Test URL:";
            this.label2.TextAlign = ContentAlignment.MiddleRight;
            this.cbxPattern.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
            this.cbxPattern.FormattingEnabled = true;
            this.cbxPattern.Location = new Point(0x57, 11);
            this.cbxPattern.Name = "cbxPattern";
            this.cbxPattern.Size = new Size(0x14e, 0x15);
            this.cbxPattern.TabIndex = 1;
            this.cbxPattern.TextChanged += new EventHandler(this.cbxPattern_TextChanged);
            this.lblStatus.AutoSize = true;
            this.lblStatus.Font = new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0);
            this.lblStatus.Location = new Point(15, 0x4b);
            this.lblStatus.Name = "lblStatus";
            this.lblStatus.Size = new Size(0x2c, 13);
            this.lblStatus.TabIndex = 5;
            this.lblStatus.Text = "Status";
            base.AutoScaleDimensions = new SizeF(6f, 13f);
          //  base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x1b2, 0x6a);
            base.Controls.Add(this.lblStatus);
            base.Controls.Add(this.cbxPattern);
            base.Controls.Add(this.label2);
            base.Controls.Add(this.label1);
            base.Controls.Add(this.btnSave);
            base.Controls.Add(this.txtURL);
            this.Font = new Font("Tahoma", 8.25f, FontStyle.Regular, GraphicsUnit.Point, 0);
          //  base.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            base.KeyPreview = true;
            base.MaximizeBox = false;
            this.MaximumSize = new Size(0x780, 140);
            this.MinimumSize = new Size(420, 140);
            base.Name = "UIARRuleTester";
            base.StartPosition = FormStartPosition.CenterParent;
            this.Text = "Test URL-Matching Expression";
            base.FormClosed += new FormClosedEventHandler(this.UIARRuleTester_FormClosed);
            base.Shown += new EventHandler(this.UIARRuleTester_Shown);
            base.KeyDown += new KeyEventHandler(this.UIARRuleTester_KeyDown);
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        private bool isValidIfREGEX(string sRule)
        {
            if ((sRule.Length > 6) && sRule.StartsWith("REGEX:", StringComparison.OrdinalIgnoreCase))
            {
                string pattern = sRule.Substring(6);
                if (pattern == ".*")
                {
                    pattern = "^.+$";
                }
                try
                {
                    new Regex(pattern);
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }

        private void UIARRuleTester_FormClosed(object sender, FormClosedEventArgs e)
        {
            string sValue = this.txtURL.Text.Trim();
            if ((sValue.Length < 1) || !sValue.Contains("://"))
            {
                sValue = null;
            }
            FiddlerApplication.Prefs.SetStringPref("fiddler.ephemeral.autoresponder.LastTestURI", sValue);
        }

        private void UIARRuleTester_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                e.SuppressKeyPress = e.Handled = true;
                base.DialogResult = DialogResult.Cancel;
            }
        }

        private void UIARRuleTester_Shown(object sender, EventArgs e)
        {
            this.cbxPattern.SelectionLength = 0;
            this.cbxPattern.SelectionStart = this.cbxPattern.Text.Length;
        }
    }
}

